import { createWebHashHistory, createRouter } from 'vue-router'

import Layout from '../views/Main.vue'
import Login from '../views/login/Login.vue'

const routes = [
    {
        path: '/',
        component: Layout,
        name: 'main',
        redirect: '/dashboard',
        children: [
            {
                name: 'Dashboard',
                path: 'dashboard',
                component: () => import('@/views/dashboard/index.vue'),
                meta: { title: '数据统计', icon: 'Calendar', path: '/dashboard' }
            },
            {
                name: 'user',
                path: 'user',
                meta: { title: '用户管理', icon: 'Reading' },
                children: [
                    {
                        path: 'index',
                        name: 'UserIndex',
                        component: () => import('@/views/user/index.vue'),
                        meta: { title: '用户列表', icon: 'User', path: '/user/index' }
                    },
                ]
            },
            {
                name: 'material',
                path: 'material',
                meta: { title: '素材管理', icon: 'Reading' },
                children: [
                    {
                        path: 'statistic',
                        name: 'materialStatistic',
                        component: () => import('@/views/material/statistic.vue'),
                        meta: { title: '素材统计', icon: 'Reading', path: '/material/statistic' }
                    },
                    {
                        path: 'index',
                        name: 'materialIndex',
                        component: () => import('@/views/material/index.vue'),
                        meta: { title: '素材列表', icon: 'Reading', path: '/material/index' }
                    }
                ]
            },
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    },

]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')

    if (!token && to.path !== '/login') {
        next('/login')
    } else if (token && to.path === '/login') {
        next('/')
    } else {
        next()
    }
})

export default router